/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gride.events;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author lukasz
 */
public class EventManager
{
    HashMap<String, List<EventListener>> listeners;

    /**
     *
     */
    public EventManager()
    {
        listeners = new HashMap<String, List<EventListener>>();
    }


    /**
     *
     * @param eventID
     * @param listener
     */
    synchronized public void addListener(String eventID, EventListener listener)
    {
        // make sure a list of listeners for this event already exists
        if (!listeners.containsKey(eventID))
            listeners.put(eventID, new ArrayList<EventListener>());

        // add the new listener to the list
        listeners.get(eventID).add(listener);
    }


    /**
     * 
     * @param listener
     */
    synchronized public void removeListener(EventListener listener)
    {
        // go through all lists, locate the listener and remove it
        for (List<EventListener> list : listeners.values())
            for (EventListener l : list)
                if (listener == l)
                {
                    list.remove(l);
                    break;
                }
    }

    /**
     *
     * @param source
     */
    synchronized public void removeAllListenersFrom(Object source)
    {
        ArrayList<EventListener> removeList = new ArrayList<EventListener>();

        // go through all lists, locate listeners added by the source
        for (List<EventListener> list : listeners.values())
            for (EventListener l : list)
                if (l.whoIsListening() == source)
                    removeList.add(l);

        // remove all the located listeners
        for (EventListener l : removeList)
            removeListener(l);
    }


    /**
     *
     * @param eventID
     * @param args
     */
    synchronized public void raiseEvent(String eventID, Object[] args)
    {
        // notify everybody listening to this event
        if (listeners.containsKey(eventID))
            for (EventListener listener : listeners.get(eventID))
                listener.eventRaised(eventID, args);
    }

}
